package cn.yujiago.shiro.service.impl;

import cn.yujiago.shiro.domain.RoleDO;
import cn.yujiago.shiro.mapper.RoleMapper;
import cn.yujiago.shiro.pojo.LayuiResult;
import cn.yujiago.shiro.pojo.LayuiTableResult;
import cn.yujiago.shiro.pojo.RoleNode;
import cn.yujiago.shiro.service.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleMapper roleMapper;
    @Resource
    private PageHelper pageHelper;

    @Override
    public List<RoleDO> getRoles(Long userId) {
        return roleMapper.selectRoles(userId);
    }

    @Override
    public LayuiTableResult<RoleDO> getRolesByCondition(int page, int limit) {
        // 1、设置分页信息，包括当前页数和每页显示的总计数
        pageHelper.startPage(page, limit);

        List<RoleDO> roleDOS = roleMapper.selectAll();

        PageInfo<RoleDO> pageInfo = new PageInfo<>(roleDOS);

        LayuiTableResult<RoleDO> result = new LayuiTableResult<>();
        result.setCode(0);
        result.setMsg("查询成功！");
        result.setData(roleDOS);
        result.setCount(pageInfo.getSize());

        return result;
    }

    @Override
    public List<RoleNode> getRolesByUserId(Long userId) {

        // 查出所有角色
        List<RoleDO> allRoles = roleMapper.selectAll();

        // 查出该用户所拥有的角色
        List<RoleDO> roles = roleMapper.selectRoles(userId);

        List<RoleNode> resultList = new ArrayList<>();

        for(RoleDO role : allRoles){

            RoleNode node = new RoleNode();
            node.setId(role.getId());
            node.setRoleName(role.getRoleName());
            node.setRoleSign(role.getRoleSign());

            if(roles.contains(role)){
                node.setChecked(true);
            }else{
                node.setChecked(false);
            }

            resultList.add(node);
        }

        return resultList;
    }

    @Override
    public LayuiResult updateUserRole(Long userId, List<Long> roleIds) {

        // 删除用户已拥有的角色
        roleMapper.deleteUserRoleByUserId(userId);
        if (roleIds != null) {
            // 插入更改的用户角色
            roleMapper.insertUserRole(userId, roleIds);
        }

        return LayuiResult.build(200, "执行成功！");
    }

}
